package com.jus.player.activity.my;


import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.api.OkHttpHelper._TOKEN;
import static com.jus.player.util.CommonUtils.showToast;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import androidx.annotation.Nullable;

import com.alibaba.fastjson2.JSONObject;
import com.bumptech.glide.Glide;
import com.google.android.gms.common.util.CollectionUtils;
import com.google.gson.Gson;
import com.jus.player.R;
import com.jus.player.activity.BaseActivity;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.entity.Feedback;
import com.jus.player.util.CommonUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 观看历史页面
 */
public class FeedbackActivity extends BaseActivity {

    private static final int MAX_IMAGES = 3;
    private static final int REQUEST_CODE_PICK_IMAGE = 1001;

    private Spinner feedbackTypeSpinner;
    private EditText feedbackContent;
    private LinearLayout imageContainer;
    private EditText contactInfo;
    private Button submitButton;

    private List<Uri> selectedImages = new ArrayList<>();

    @Override
    protected int initLayout() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initView() {
        //返回按钮
        RelativeLayout back = findViewById(R.id.system_back);
        back.setOnClickListener(view -> finish());

        feedbackTypeSpinner = findViewById(R.id.feedback_type_spinner);
        feedbackContent = findViewById(R.id.feedback_content);
        imageContainer = findViewById(R.id.image_container);
        contactInfo = findViewById(R.id.contact_info);
        submitButton = findViewById(R.id.submit_feedback);
        setupFeedbackTypes();
        setupImageUpload();
        setupSubmitButton();
    }

    @Override
    protected void initData() {

    }

    private void setupFeedbackTypes() {
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this,
                R.array.feedback_types,
                android.R.layout.simple_spinner_item
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        feedbackTypeSpinner.setAdapter(adapter);
    }

    private void setupImageUpload() {
        ImageView addImageBtn = findViewById(R.id.add_image_btn);
        addImageBtn.setOnClickListener(v -> {
            if (selectedImages.size() >= MAX_IMAGES) {
                showToast(this, "最多上传" + MAX_IMAGES + "张图片");
                return;
            }
            // 启动图片选择器
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)),
                    REQUEST_CODE_PICK_IMAGE);
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK) {
            if (data != null) {
                if (data.getClipData() != null) {
                    // 多选
                    int count = data.getClipData().getItemCount();
                    for (int i = 0; i < count && selectedImages.size() < MAX_IMAGES; i++) {
                        Uri imageUri = data.getClipData().getItemAt(i).getUri();
                        selectedImages.add(imageUri);
                        addImageToContainer(imageUri);
                    }
                } else if (data.getData() != null) {
                    // 单选
                    Uri imageUri = data.getData();
                    selectedImages.add(imageUri);
                    addImageToContainer(imageUri);
                }
            }
        }
    }

    private void addImageToContainer(Uri imageUri) {
        ImageView imageView = new ImageView(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                dpToPx(80), dpToPx(80));
        params.setMargins(dpToPx(8), 0, dpToPx(8), 0);
        imageView.setLayoutParams(params);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        Glide.with(this)
                .load(imageUri)
                .into(imageView);

        // 添加删除按钮
        imageView.setOnClickListener(v -> {
            selectedImages.remove(imageUri);
            imageContainer.removeView(imageView);
        });

        imageContainer.addView(imageView, imageContainer.getChildCount() - 1);
    }

    private void setupSubmitButton() {
        submitButton.setOnClickListener(v -> {
            String feedbackType = feedbackTypeSpinner.getSelectedItem().toString();
            String content = feedbackContent.getText().toString().trim();
            String contact = contactInfo.getText().toString().trim();
            if (feedbackType.isEmpty() || getString(R.string.select_feedback_type).equals(feedbackType)) {
                CommonUtils.showToastPos(this, getString(R.string.select_feedback_type), 400, true);
                return;
            }
            if (content.isEmpty()) {
                CommonUtils.showToastPos(this, getString(R.string.hint_fill_content), 400, true);
                return;
            }
            if (content.length() < AppConfig.INT_15) {
                CommonUtils.showToastPos(this, getString(R.string.hint_content_length), 400, true);
                CommonUtils.showToastPos(this, getString(R.string.hint_content_length), AppConfig.INT_200, true);
                return;
            }
            submitFeedback(feedbackType, content, contact);
        });
    }

    private void submitFeedback(String type, String content, String contact) {
        // 显示加载中
        /*ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.hint_submiting));
        progressDialog.setCancelable(false);
        progressDialog.show();*/
        CommonUtils.showLoading(this);

        // 构建反馈对象
        Feedback feedback = new Feedback();
        feedback.setType(type);
        feedback.setContent(content);
        feedback.setContactInfo(contact);
        feedback.setDeviceInfo(getDeviceInfo());
        feedback.setAppVersion(getAppVersion());

        // 如果有图片，先上传图片
        if (!selectedImages.isEmpty()) {
            uploadImages(selectedImages, new ImageUploadCallback() {
                @Override
                public void onSuccess(List<String> imageUrls) {
                    if (!CollectionUtils.isEmpty(imageUrls)) {
                        StringBuilder sb = new StringBuilder();
                        for (String imageUrl : imageUrls) {
                            sb.append(imageUrl);
                            sb.append(",");
                        }
                        feedback.setImageUrls(sb.substring(0, sb.length() - 1));
                    }
                    sendFeedbackToServer(feedback);
                }

                @Override
                public void onFailure(String error) {
                    CommonUtils.hideLoading(FeedbackActivity.this);
                }
            });
        } else {
            sendFeedbackToServer(feedback);
        }
    }

    private void sendFeedbackToServer(Feedback feedback) {
        // 这里使用Retrofit发送反馈到服务器
        String json = new Gson().toJson(feedback);
        //Map<String, String> map = gson.fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
        OkHttpHelper.getInstance(this).postJsonAsync(ApiConfig.SUBMIT_FEEDBACK, json,
                new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String res) {
                        CommonUtils.hideLoading(FeedbackActivity.this);
                        CommonUtils.showToastAsync(FeedbackActivity.this, getString(R.string.submit_ok));
                        finish();
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        CommonUtils.hideLoading(FeedbackActivity.this);
                        CommonUtils.showToastAsync(FeedbackActivity.this, e.getMessage());
                    }
                });

    }

    private String getDeviceInfo() {
        return Build.MANUFACTURER + " " + Build.MODEL + ", Android " + Build.VERSION.RELEASE;
    }

    private String getAppVersion() {
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            return pInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "unknown";
        }
    }

    private int dpToPx(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

    interface ImageUploadCallback {
        void onSuccess(List<String> imageUrls);

        void onFailure(String error);
    }


    /**
     * 网络请求-上传图片
     */
    public void uploadImages(List<Uri> imageUris, ImageUploadCallback callback) {
        // 1. 创建多部分构建器
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        // 2. 添加图片
        for (Uri uri : imageUris) {
            InputStream inputStream = null;
            try {
                inputStream = getContentResolver().openInputStream(uri);
                byte[] bytes = readStream(inputStream);
                builder.addFormDataPart(
                        "images", // 后端接收的字段名
                        "image_" + System.currentTimeMillis() + ".jpg", // 文件名
                        RequestBody.create(MediaType.parse("image/*"), bytes)
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        // 3. 构建请求
        Request request = new Request.Builder()
                .url(ApiConfig.BASE_URL + ApiConfig.UPLOAD_IMAGES)
                .addHeader(_TOKEN, CommonUtils.findFromSp(this, _TOKEN))
                .post(builder.build())
                .build();

        // 4. 发送请求
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jo = JSONObject.parseObject(result);
                callback.onSuccess(jo.getList(_DATA, String.class));

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        getWindow().setStatusBarColor(Color.WHITE);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        );
    }

    @Override
    protected void onPause() {
        super.onPause();
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        );
    }


    private byte[] readStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        return outputStream.toByteArray();
    }

}